<!--
 * @Author: 
 * @Date: 2021-12-28 20:15:23
 * @LastEditors: Joe Yan
 * @LastEditTime: 2021-12-28 20:39:29
 * @Description: file content
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script>

        /***
         * 1. 拷贝原函数
         * 2. 返回拷贝的原函数
         * 3. 调用拷贝的函数
         * **/

        Function.prototype.myBind = function(target, ...params) {
            const thisFn = this; // thisFn拷贝原函数，相当于一个闭包中的变量，给fToBind执行时调用

            let fToBind = function(...others) {
                // 判断fToBing是使用new关键字调用
                const isNew = this instanceof thisFn;

                // 如果是通过new关键字调用，就把this（fToBind的实例对象）
                const context = isNew ? this : Object(target);
                return thisFn.call(context, ...params, ...others)
            }

            fToBind.prototype = Object.create(thisFn.prototype);

            return fToBind;
        }

        function foo(x) {
            console.log(x * 2);
        }

        var obj = {
            name: "Mike"
        } 

        let bindFn = foo.myBind(obj);
        bindFn(5);

        let m = new bindFn(8);
        console.log(11,m);
    </script>
</body>
</html>